package org.fengling.readingplatform.common.log.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.fengling.readingplatform.common.log.annotation.Log;
import org.fengling.readingplatform.common.log.service.AsyncOperLogService;
import org.fengling.readingplatform.common.log.utils.LogUtil;
import org.fengling.readingplatform.model.entity.system.SysOperLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class LogAspect {

    @Autowired
    private AsyncOperLogService operLogService;

    // 环绕通知
    @Around(value = "@annotation(sysLog)")
    public Object doAroundAdvice(ProceedingJoinPoint joinPoint, Log sysLog){//参数、注解机制

        // 业务方法调用之前封装数据
        SysOperLog sysOperLog = new SysOperLog();
        LogUtil.beforeHandleLog(sysLog, joinPoint, sysOperLog);
        // 业务方法
        Object proceed = null;
        try {
            proceed = joinPoint.proceed();
            //调用业务方法之后封装数据
            LogUtil.afterHandlLog(sysLog, proceed, sysOperLog, 0, null);
        } catch (Throwable e) {
            e.printStackTrace();
            LogUtil.afterHandlLog(sysLog, proceed, sysOperLog, 1, e.getMessage());
            throw new RuntimeException(e);
        }
        // 调用service方法把日志信息添加到数据库中
        System.out.println(sysOperLog)   ;
        operLogService.saveSysOperLog(sysOperLog);
        return proceed;
    }

}
